// 视频列表管理
class VideoList {
    constructor() {
        this.videosGrid = document.getElementById('videosGrid');
        this.searchInput = document.getElementById('searchInput');
        this.sortSelect = document.getElementById('sortSelect');
        this.loadingSpinner = document.getElementById('loadingSpinner');
        this.page = 1;
        this.pageSize = 12;
        this.hasMore = true;
        this.isLoading = false;

        // 初始化
        this.init();
    }

    async init() {
        // 添加事件监听
        this.addEventListeners();
        
        // 加载初始视频
        await this.loadVideos();
    }

    addEventListeners() {
        // 搜索输入
        this.searchInput.addEventListener('input', this.debounce(() => {
            this.page = 1;
            this.hasMore = true;
            this.videosGrid.innerHTML = '';
            this.loadVideos();
        }, 500));

        // 排序选择
        this.sortSelect.addEventListener('change', () => {
            this.page = 1;
            this.hasMore = true;
            this.videosGrid.innerHTML = '';
            this.loadVideos();
        });

        // 滚动加载
        window.addEventListener('scroll', this.debounce(() => {
            if (this.hasMore && !this.isLoading) {
                const scrollPosition = window.innerHeight + window.scrollY;
                const bodyHeight = document.body.offsetHeight;
                if (scrollPosition >= bodyHeight - 100) {
                    this.loadVideos();
                }
            }
        }, 200));
    }

    async loadVideos() {
        if (this.isLoading) return;
        
        this.isLoading = true;
        this.showLoadingSpinner();

        try {
            const search = this.searchInput.value.trim();
            const sort = this.sortSelect.value;
            
            const response = await fetch(`/api/videos?page=${this.page}&pageSize=${this.pageSize}&search=${search}&sort=${sort}`);
            const data = await response.json();
            
            // 添加视频卡片
            data.videos.forEach(video => {
                this.createVideoCard(video);
            });

            // 更新分页状态
            this.page++;
            this.hasMore = data.videos.length === this.pageSize;
        } catch (error) {
            console.error('加载视频失败:', error);
        } finally {
            this.isLoading = false;
            this.hideLoadingSpinner();
        }
    }

    createVideoCard(video) {
        const card = document.createElement('div');
        card.className = 'video-card';
        card.innerHTML = `
            <img src="${video.thumbnail || '/images/default-thumbnail.jpg'}" alt="${video.title}" class="video-thumbnail">
            <div class="video-info">
                <h3 class="video-title">${video.title}</h3>
                <div class="video-meta">
                    <div class="video-author">
                        <img src="${video.author?.avatar || '/images/default-avatar.png'}" alt="作者头像">
                        <span>${video.author?.nickname || '未知用户'}</span>
                    </div>
                    <div class="video-stats">
                        <span><i class="fas fa-eye"></i> ${video.views}</span>
                        <span><i class="fas fa-heart"></i> ${video.likes}</span>
                        <span><i class="fas fa-comment"></i> ${video.comments}</span>
                    </div>
                </div>
            </div>
        `;

        // 添加点击事件
        card.addEventListener('click', () => {
            window.location.href = `/video/${video.id}`;
        });

        this.videosGrid.appendChild(card);
    }

    showLoadingSpinner() {
        this.loadingSpinner.style.display = 'block';
    }

    hideLoadingSpinner() {
        this.loadingSpinner.style.display = 'none';
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
}

// 初始化视频列表
document.addEventListener('DOMContentLoaded', () => {
    new VideoList();
}); 